{extend name="layout/iframe_layout" /}

{block name="title"}我的笔记{/block}
{block name="style"}
<style>

</style>
{/block}

{block name="content"}

<div id="app" >
    <div class="app-container">
        {include file="public/search_form" /}

        <div class="action-btns">
            <el-button-group>
                <el-button type="info" size="mini" icon="el-icon-refresh" @click="search">刷新</el-button>
                <el-button type="success" size="mini" icon="el-icon-plus" @click="openDialog">新增
                </el-button>

            </el-button-group>
            <el-button-group>
                <el-button type="primary" size="mini" icon="el-icon-menu" @click="showColumnSetting = true">字段配置</el-button>
            </el-button-group>

        </div>
        <el-table
                ref="multipleTable"
                v-loading="listLoading"
                :data="list"
                element-loading-text="Loading"
                border
                fit
                highlight-current-row
                tooltip-effect="dark"
                style="width: 100%"
                align="center"
                @selection-change="handleSelectionChange"
        >
            <!--      <el-table-column type="selection" width="55" align="center" prop="id"/>-->
            {include file="public/table_column" /}
            <el-table-column align="center" prop="created_at" label="操作" fixed="right" width="170">
                <template v-slot:default="{scope,row}">
                    <el-row type="flex" justify="space-around">
                        <el-button
                                size="mini"
                                type="info"
                                title="查看"
                                icon="el-icon-view"
                                circle
                                @click="preview(row)"
                        ></el-button>
                        <el-button
                                size="mini"
                                type="primary"
                                title="修改"
                                icon="el-icon-edit"
                                circle
                                @click="openDialog(row)"
                        ></el-button>
                        <el-button type="danger" size="mini" icon="el-icon-delete" circle @click="del(row)"></el-button>


                    </el-row>
                </template>
            </el-table-column>
        </el-table>

        <!-- 字段设置对话框 -->
        {include file="public/show_column_setting" /}
        <!--分页-->
        {include file="public/pagination" /}
    </div>

    <!-- 弹窗：新增/编辑 -->
    <el-dialog
            :title="form.id ? '编辑' : '新增'"
            :visible.sync="dialogVisible"
            width="80%"
            top="5vh"
            :close-on-click-modal="false"
            append-to-body
    >
        <el-form :model="form" label-width="100px">
            <el-form-item label="名称" required>
                <el-input v-model="form.title" autocomplete="off" placeholder="请输入"  />
            </el-form-item>
            <el-form-item label="内容" required>
                <div id="markdown-editor">
                    <textarea style="display:none;"></textarea>
                </div>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="saveData">保存</el-button>
        </div>
    </el-dialog>

    <el-dialog
      title="内容预览"
      :visible.sync="previewVisible"
      width="80%"
      top="5vh"
      :close-on-click-modal="false"
      append-to-body
    >
         <div>
             <el-dropdown @command="handleExport">
              <el-button size="mini" type="primary">
                导出 <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="html">导出 HTML</el-dropdown-item>
                <el-dropdown-item command="doc">导出 Word</el-dropdown-item>
                <el-dropdown-item command="pdf">导出 PDF</el-dropdown-item>
                <el-dropdown-item command="markdown">导出 Markdown</el-dropdown-item>
                <el-dropdown-item command="png">导出 PNG</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
        </div>



      <div id="markdown-preview" style="padding: 10px; border: 1px solid #ccc;"></div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="previewVisible = false">关闭</el-button>
        </div>
    </el-dialog>
</div>
{/block}

{block name="script"}

<link rel="stylesheet" href="/static/lib/editor.md-1.5.0/css/editormd.min.css" />
<link rel="stylesheet" href="/static/lib/editor.md-1.5.0/css/editormd.preview.css" />
<script src="/static/lib/jquery/jquery.min.js"></script>
<script src="/static/lib/editor.md-1.5.0/editormd.min.js"></script>
<script src="/static/lib/editor.md-1.5.0/lib/marked.min.js"></script>
<!-- 图表功能依赖（可选） -->
<script src="/static/lib/editor.md-1.5.0/lib/raphael.min.js"></script>
<script src="/static/lib/editor.md-1.5.0/lib/underscore.min.js"></script>
<script src="/static/lib/editor.md-1.5.0/lib/sequence-diagram.min.js"></script>
<script src="/static/lib/editor.md-1.5.0/lib/flowchart.min.js"></script>
<script src="/static/lib/editor.md-1.5.0/lib/jquery.flowchart.min.js"></script>
<!-- 代码美化库（可选） -->
<script src="/static/lib/editor.md-1.5.0/lib/prettify.min.js"></script>
<!--导出图片需要-->
<script src="/static/js/html2canvas.min.js"></script>
<!--导出PDF使用-->
<script src="/static/js/html2pdf.bundle.min.js"></script>
<!--导出功能-->
<script src="/static/js/export-service.js"></script>


<script>
    Vue.mixin(commonMethods);//引入公共方法
    var api_base = '/note_books';
    new Vue({
        el: '#app',
        data() {
            return {
               dialogVisible: false,
                previewVisible: false,
                previewContent: '',
                previewTitle: '',
                editor: null,
                form: {
                    id: 0,
                    title:'',
                    content:'',
                },

                listQuery:{
                    page: 1,
                    limit: 10
                },
                search_fields: [

                ],
                multipleSelection: [],
                el_table_column: [],
                list: null,
                listLoading: true,
                total: 0,
                searchForm: {
                    keyword: '',
                    sort: '',
                },

                isAllChecked: true, // 是否全选
                isIndeterminate: true, // 全选框是否为不确定状态
                checkList: [], // 选择的字段名称（标签）
                showColumnSetting: false,
                visibleColumns: [], // 当前显示的列配置
            };
        },
        methods: {
             openDialog(row) {
                if (row){
                    this.form = Object.assign({}, row);
                }else{
                    Object.keys(this.form).forEach(key => this.form[key] = '');
                    this.form.id = 0;
                    this.form.title = '';
                    this.form.content = '';
                }
                this.dialogVisible = true;
                this.$nextTick(() => {
                    if (!this.editor) {
                        this.initEditor(this.form.content); // 首次初始化
                    } else {
                        // 等 editor 初始化成功后再 setMarkdown（确保 editor 已存在）
                        setTimeout(() => {
                            if (this.editor && this.editor.setMarkdown) {
                                this.editor.setMarkdown(this.form.content || '');
                            } else {
                                console.warn('Editor not ready yet when editing');
                            }
                        }, 200); // 延迟一点点时间
                    }
                });
            },

            initEditor(content = '') {
                this.editor = editormd("markdown-editor", {
                    width: "100%",
                    height: 400,
                    emoji: false,
                    path: "/static/lib/editor.md-1.5.0/lib/",
                    //markdown: content,
                    codeFold: true,
                    saveHTMLToTextarea: true,
                    flowChart: true,       // 开启流程图支持
                    sequenceDiagram: true, // 开启时序图支持

                    onload: () => {
                    // 只有初始化成功后，才能调用 setMarkdown
                    if (this.editor && this.editor.setMarkdown) {
                        this.editor.setMarkdown(content || '');
                    } else {
                        console.warn("Editor is not fully ready");
                    }
                }
                });
            },
            preview(row) {
              this.previewContent = row.content;
              this.previewTitle = row.title;
              this.previewVisible = true;

              this.$nextTick(() => {
                // 清空容器，插入一个新的 div
                const container = document.getElementById('markdown-preview');
                container.innerHTML = '<div id="markdown-preview-inner"></div>';

                // 再次调用 markdownToHTML 渲染新的内容
                editormd.markdownToHTML("markdown-preview-inner", {
                  markdown: this.previewContent,
                  saveHTMLToTextarea: true,
                  htmlDecode: "style,script,iframe",
                  toc: false,
                  emoji: true,
                  taskList: true,
                  tex: true,
                  flowChart: true,
                  sequenceDiagram: true,
                });
              });
            },
            saveData() {
                this.form.content = this.editor.getMarkdown(); // 或 this.editor.getHTML()
                // 接下来的保存逻辑保持不变
                (this.form.id? put(api_base+'/save', this.form) : post(api_base+'/save', this.form))
                    .then(res => {
                        if (res.code != 0) {
                            this.$message.error(res.msg || '保存失败');
                            return;
                        }
                        this.$message.success(this.form.id ? '已更新' : '已新增');
                        this.dialogVisible = false;
                        this.fetchData(true);
                    }).catch(error => {
                    console.error('保存功能失败:', error);
                });
            },
             // 导出功能
            handleExport(type) {
              const container = document.getElementById("markdown-preview-inner");
              const markdown = this.previewContent;
              const title = this.previewTitle;

              if (['html', 'doc'].includes(type)) {
                ExportService.export({ type, content: container.innerHTML, filename:  title+`_${Date.now()}` });
              } else if (type === 'pdf' || type === 'png') {
                ExportService.export({ type, content: container, filename: title+ `_${Date.now()}` });
              } else if (type === 'markdown') {
                ExportService.export({ type, content: markdown, filename:  title+`_${Date.now()}` });
              }
            }
        },
        mounted() {
            this.fetchListConfig();
            this.fetchData();
        }
    });

</script>
{/block}
